/* eslint-disable no-unused-vars */
import { routers as constRouters } from '@/router/index'
import { cloneDeep } from 'lodash'

// 判断是否有权限访问该菜单
function hasPermission(menus, route) {
  if (route.name) {
    const currMenu = getMenu(route.name, menus)
    if (currMenu != null) {
      // 设置菜单的标题、图标和可见性
      if (currMenu.title != null && currMenu.title !== '') {
        route.meta.title = currMenu.title
      }
      if (currMenu.icon != null && currMenu.title !== '') {
        route.meta.icon = currMenu.icon
      }
      if (currMenu.hidde != null) {
        route.hidden = currMenu.hidden !== 0
      }
      if (currMenu.sort != null && currMenu.sort !== '') {
        route.sort = currMenu.sort
      }
      return true
    } else {
      route.sort = 0
      if (route.hidden !== undefined && route.hidden === true) {
        route.sort = -1
        return true
      } else {
        return false
      }
    }
  } else {
    return true
  }
}

// 根据路由名称获取菜单
function getMenu(name, menus) {
  for (let i = 0; i < menus.length; i++) {
    const menu = menus[i]
    if (name === menu.name) {
      return menu
    }
  }
  return null
}

// 对菜单进行排序
function sortRouters(accessedRouters) {
  for (let i = 0; i < accessedRouters.length; i++) {
    const router = accessedRouters[i]
    if (router.children && router.children.length > 0) {
      router.children.sort(compare('sort'))
    }
  }
  accessedRouters.sort(compare('sort'))
}

// 降序比较函数
function compare(p) {
  return function(m, n) {
    const a = m[p]
    const b = n[p]
    return b - a
  }
}

const state = {
  routers: []
}

const mutations = {
  SET_ROUTERS: (state, routers) => {
    state.routers = routers
  },
  RESET_ROUTERS: (state, routers) => {
    state.routers = routers
  }
}

const actions = {
  GenerateRoutes({ commit }) {
    return new Promise(resolve => {
      const permissions = JSON.parse(localStorage.getItem('userInfo'))?.permissions.permissions || []
      const newRouters = cloneDeep(constRouters)
      // 路由权限控制，目前只做到第三层菜单级别，后续如果有四级菜单，需要再进行遍历判断
      newRouters.map((item) => {
        if (permissions.includes(item.name)) item.hidden = false
        if (item.children) {
          item.children.map((chItem) => {
            if (permissions.includes(chItem.name)) chItem.hidden = false
            if (chItem.children) {
              chItem.children.map((graItem) => {
                if (permissions.includes(graItem.name)) graItem.hidden = false
              })
            }
          })
        }
      })
      commit('SET_ROUTERS', newRouters)
      resolve()
    })
  },
  ResetRouters({ commit }) {
    commit('RESET_ROUTERS', [])
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
